<template>
  <van-sku
    v-model="show"
    :sku="sku"
    :goods="goods"
    :goods-id="goodsId"
    :quota="quota"
    :quota-used="quotaUsed"
    :hide-stock="false"
    :initial-sku="initialSku"
    @buy-clicked="onBuyClicked"
    @add-cart="onAddCartClicked"
    @sku-selected="skuSelect"
  />
</template>
<script>
import { Sku } from "vant";
import { Toast } from "vant";
import { apiVerifyLogin } from "@/api/user";
import { YM_LOGIN_BACK_URL } from "@/store/constant";
export default {
  name: "Sku",
  components: {
    [Sku.name]: Sku,
    [Toast.name]: Toast
  },
  data() {
    return {
      show: false,
      quota: 0,
      quotaUsed: 0,
      goodsId: 29,
      initialSku: {
        // 键：skuKeyStr（sku 组合列表中当前类目对应的 key 值）
        // 值：skuValueId（规格值 id）
        s1: 1,
        s2: 2,
        // 初始选中数量
        selectedNum: 2
      },
      sku: {
        // 所有sku规格类目与其值的从属关系，比如商品有颜色和尺码两大类规格，颜色下面又有红色和蓝色两个规格值。
        // 可以理解为一个商品可以有多个规格类目，一个规格类目下可以有多个规格值。
        tree: [],
        // 所有 sku 的组合列表，比如红色、M 码为一个 sku 组合，红色、S 码为另一个组合
        list: [],
        none_sku: false, // 是否无规格商品
        hide_stock: false // 是否隐藏剩余库存
      },
      goods: {}
    };
  },

  methods: {
    selectSku(spu) {
      console.log("selectSku spu", spu);
      this.sku.list = spu.sku.list;
      this.sku.tree = spu.sku.tree;
      this.goodsId = spu.id;
      this.goods = {
        title: spu.title,
        picture: this.sku.tree[0].v[0].imgUrl
      };
      this.show = true;
    },
    onBuyClicked(skuData) {
      apiVerifyLogin().then(res => {
        if (res.status == 0) {
          console.log(skuData);
          const orderSkus = [];
          orderSkus.push({
            id: skuData.selectedSkuComb.id,
            title: this.goods.title,
            price: skuData.selectedSkuComb.price,
            desc: skuData.selectedSkuComb.title,
            num: skuData.selectedNum,
            imgUrl: skuData.selectedSkuComb.imgUrl
          });
          this.$router.push({
            name: "order",
            query: {
              orderSkus: JSON.stringify(orderSkus)
            }
          });
        } else {
          sessionStorage.setItem(YM_LOGIN_BACK_URL, location.href);
          this.$router.push({
            name: "login"
          });
        }
      });
    },
    onAddCartClicked(skuData) {
      console.log(skuData);
    },
    skuSelect(selectSku) {
      console.log("", selectSku);
      if (selectSku.selectedSkuComb != null) {
        this.$emit("receiveSku", selectSku.selectedSkuComb.title);
      }
    }
  }
};
</script>
